var tool = require("./tool");

exports.checkServerIdle = function (map, params, fn) {
    var self = this,
        url = map.pop();

    if (url) {
        self.postToCheckIdle(url, params, {
            success: function () {
                self.checkServerIdle(map, params, fn);
            },
            error: function () {
                self.postToCheckIdle.apply(self, arguments);
            }
        });
    } else {
        fn();
    }
};

exports.postToCheckIdle = function (url, params, fns) {
    var request = require("request");

    request.post({
        url: url,
        form: params
    }, function (err, httpResponse, body) {
        var statusCode = httpResponse && httpResponse.toJSON().statusCode;

        try {
            body = body && JSON.parse(body);
        } catch (e) {
            body = {
                no: -1,
                msg: "server is something wrong!"
            }
        }

        if (body.no != 0 || statusCode != 200 || err) {
            if (body && body.no) console.log("\n" + url + " " + JSON.stringify(body));
            if (statusCode != 200) console.log("statusCode: " + statusCode);

            tool.log("\nwait for try again after 15s...");
            tool.startWaitLog();

            setTimeout(function () {
                tool.stopWaitLog();
                fns.error(url, params, fns);
            }, 15 * 1000);
        } else {
            fns.success();
        }
    });
};

exports.postToDel = function (map, params, fn) {
    var self = this,
        url = map.shift();

    if (url) {
        self.postToCheckIdle(url, params, {
            success: function () {
                self.postToDel(map, params, fn);
            },
            error: function () {
                self.postToCheckIdle.apply(self, arguments);
            }
        })
    } else {
        fn();
    }
};